package com.emuporium.gymrat.server.program;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emuporium.gymrat.server.data.Program;
import com.emuporium.gymrat.server.data.ProgramDB;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

@SuppressWarnings("serial")
public class ProgramCreateServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String name = request.getParameter("name");
		String desc = request.getParameter("desc");
		String author = request.getParameter("author");
		Program program = new Program();
		program.setName(name);
		program.setDescription(desc);
		program.setAuthor(author);

		User user = UserDB.selectUser(request.getRemoteUser());
		String url = "";
		String message = "";

		if (user != null) {
			int result = ProgramDB.insert(program, user.getId());
			if (result > 0) {
				request.setAttribute("redirecturl", "/routine/list");
				url = "/includes/redirect.jsp";
			}
			
			else {
				url = "/program/create.jsp";
			}
		}
		else {
			url = "/program/create.jsp";
		}

		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
}
